package com.jcbase.controller.wechat;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jcbase.core.BaseConstance;
import com.jcbase.core.auth.interceptor.AuthorityInterceptor;
import com.jcbase.core.auth.interceptor.SysLogInterceptor;
import com.jcbase.core.util.CommonUtils;
import com.jcbase.core.util.WeiXinUtils;
import com.jcbase.core.weixin.interceptor.ApiInterceptor;
import com.jcbase.model.RisebdMember;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.PropKit;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.weixin.sdk.api.SnsApi;
import com.jfinal.weixin.sdk.api.UserApi;

/**
 * @category 微信index
 * @author yiz
 *
 */
@Before(ApiInterceptor.class)
@Clear({ AuthorityInterceptor.class, SysLogInterceptor.class })
public class WechatOauthController extends Controller {
	private static final Logger logger = LoggerFactory.getLogger(WechatOauthController.class);

	//跳转到授权页面
	public void toOauth() {
		String redirect_url = getPara("redirect_url");
		logger.info("请求的连接redirect_url={}", redirect_url);
		String calbackUrl = BaseConstance.DOMAIN + "/wx/oauth?redirect_url=" + redirect_url;
		logger.info("跳转的连接calbackUrl={}", calbackUrl);
		try {
			calbackUrl = URLEncoder.encode(calbackUrl, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			logger.error("encodeUrl失败e={}", e);
		}
		String url = SnsAccessTokenApi.getAuthorizeURL(PropKit.get("appId"), calbackUrl, null, false);
		logger.info("获得的微信连接url={}", url);
		redirect(url);
	}

	/**
	 * @category 授权
	 */
	public void oauth() {
		//是否关注
		int subscribe = 0;
		//用户同意授权，获取code
		String code = getPara("code");
		String state = getPara("state");
		String redirect_url = getPara("redirect_url");
		logger.info("认证请求数据code={},state={},redirect_url={}", code, state, redirect_url);
		if (code != null) {
			String appId = ApiConfigKit.getApiConfig().getAppId();
			String secret = ApiConfigKit.getApiConfig().getAppSecret();
			//通过code换取网页授权access_token
			SnsAccessToken snsAccessToken = SnsAccessTokenApi.getSnsAccessToken(appId, secret, code);
			String token = snsAccessToken.getAccessToken();
			String openId = snsAccessToken.getOpenid();
			//拉取用户信息(需scope为 snsapi_userinfo)
			ApiResult apiResult = SnsApi.getUserInfo(token, openId);
			if (apiResult.isSucceed()) {
				//得到返回的json数据
				JSONObject jsonObject = JSON.parseObject(apiResult.getJson());
				String nickName = jsonObject.getString("nickname");
				//用户的性别，值为1时是男性，值为2时是女性，值为0时是未知
				int sex = jsonObject.getIntValue("sex");
				String city = jsonObject.getString("city");//城市
				String province = jsonObject.getString("province");//省份
				String country = jsonObject.getString("country");//国家
				String headimgurl = jsonObject.getString("headimgurl");
				String openid = jsonObject.getString("openid");
				//获取用户信息判断是否关注
				ApiResult userInfo = UserApi.getUserInfo(openId);
				if (userInfo.isSucceed()) {
					String userStr = userInfo.toString();
					subscribe = JSON.parseObject(userStr).getIntValue("subscribe");
				}
				if (CommonUtils.isNotEmpty(openid)) {//保存cookie
					setCookie(BaseConstance.OPENID_COOKIE_KEY, openid, BaseConstance.OPENID_COOKIE_MAXAGE);
				}
				if (subscribe == 0 && BaseConstance.NEED_FOLLOW) {//为关注跳转至关注页面
					redirect(PropKit.get("subscribe_url"));
				} else {
					//保存关注着会员的信息
					boolean exist = RisebdMember.me.existMember(openid);
					if (!exist) {
						logger.info("保存会员信息userInfo={}", JsonKit.toJson(userInfo));
						RisebdMember.me.saveMember(null, openId, WeiXinUtils.filterWeixinEmoji(nickName), null, null,
								sex, country, province, city, subscribe, headimgurl, 0);
					} else {
						RisebdMember.me.updateSubscribe(openid, subscribe);
					}
					redirect(redirect_url);
				}
			}
		} else {
			renderText("code is  null");
		}
	}
}
